package piwan;

import java.awt.event.MouseEvent;

import org.fenggui.Display;
import org.fenggui.event.mouse.MouseButton;

public class GuiEventHandlerBinding extends EventHandler {
	private Display display;
	private MainWindow win;
	private boolean dragging = false;
	
	private static MouseButton adaptMouseButton(int b) {
		switch(b) {
		case MouseEvent.BUTTON1: return MouseButton.LEFT;
		case MouseEvent.BUTTON2: return MouseButton.MIDDLE;
		case MouseEvent.BUTTON3: return MouseButton.RIGHT;
		default:
			assert false : b;
			return MouseButton.LEFT;
		}
	}
	
	public GuiEventHandlerBinding(MainWindow w, Display d) {
		display = d;
		win = w;
		w.addEventHandler(this);
	}
	
	public void remove() {
		win.removeEventHandler(this);
	}
	
	public boolean onMousePressed(MouseEvent e) {
		MouseButton but = adaptMouseButton(e.getButton());
		dragging = true;
		return display.fireMousePressedEvent(e.getX(), display.getHeight()-e.getY(), but, e.getClickCount());
	}
	
	public boolean onMouseReleased(MouseEvent e) {
		MouseButton but = adaptMouseButton(e.getButton());
		dragging = false;
		return display.fireMouseReleasedEvent(e.getX(), display.getHeight()-e.getY(), but, e.getClickCount());
	}
	
	public boolean onMouseMotion(MouseEvent e) {
		MouseButton but = adaptMouseButton(e.getButton());
		if(dragging)
			return display.fireMouseDraggedEvent(e.getX(), display.getHeight()-e.getY(), but, e.getClickCount());
		else
			return display.fireMouseMovedEvent(e.getX(), display.getHeight()-e.getY(), but, e.getClickCount());
	}
}
